const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const {
    queryDatabase,
    createSixNum
} = require('../utils/common')
const nodeMail = require('../utils/nodemailer')
const { generateToken } = require('../utils/token')

router.post('/login', async (req, res) => {
    try {
        let user = req.body
        let sql = `select password,account from usersinfo where email = '${user.email}' `
        let result = await queryDatabase(sql)
        if (result.length > 0) {
            if (user.password === result[0].password) {
                let sql1 = `select nickname,account,email,phone,avatarurl,spacesize,usedisk,sign,blog from usersinfo where email = '${user.email}' `
                let data = await queryDatabase(sql1)
                let token = generateToken(result[0].account) //生成token
                res.send({ msg: '登录成功', code: 200, token, data: data[0] })
            } else {
                res.send({ msg: '登录密码错误', code: 204 })
            }
        } else {
            res.send({ msg: '账户不存在，请注册账户！', code: 205 })
        }
    } catch (error) {
        res.send({ msg: error, code: 204 })
    }
})
router.post('/register', async (req, res) => {
    let user = req.body
    let sql = `select account from usersinfo where email = '${user.email}' `
    let result = await queryDatabase(sql)
    let timestamp = Date.parse(new Date());
    let account = Math.random().toString(36).substr(2); //随机生成用户专属账户
    if (result.length > 0 && result[0].account) {
        res.send({ msg: '该邮箱账号已注册，可直接登录！', code: 205 })
    } else {
        let codeSql = `select id,code from usersinfo where email = '${user.email}' `
        let codeRes = await queryDatabase(codeSql)
        if (codeRes.length > 0 && parseInt(codeRes[0].code) === parseInt(user.captcha)) {
            let updateSql = `UPDATE usersinfo  SET  password='${user.confirm}',spacesize=1024,
                    usedisk=0,date='${timestamp}',status=1,account='${account}'
                    WHERE email='${user.email}' ;`
            let rowRes = await queryDatabase(updateSql)
            if (rowRes.affectedRows) {
                let newTableSql = `CREATE TABLE IF NOT EXISTS ${account}(
                        id INT UNSIGNED AUTO_INCREMENT,
                        created VARCHAR(30),
                        path VARCHAR(255),
                        size INT(10),
                        type INT(4) ,
                        account VARCHAR(30) ,
                        PRIMARY KEY ( id )
                     )ENGINE=InnoDB DEFAULT CHARSET=utf8;`
                await queryDatabase(newTableSql)
                //创建用户文件根目录及默认文件夹
                let defaultDir = ['图片', '视频', '音频', '文档', '其他']
                let rootPath = path.join(__dirname, `../public/userRoot/${account}/`)
                let newInsertSql = `INSERT INTO ${account} (created,path,type,account) VALUES ('${timestamp}','${rootPath.replace(/\\/g, '/')}',0,'${account}');`
                await queryDatabase(newInsertSql)
                fs.mkdir(rootPath, 0777, (err) => {
                    if (!err) {
                        defaultDir.map(defaultDir => {
                            fs.mkdir(rootPath + defaultDir, 0777, async (err) => {
                                if (!err) {
                                    let newInsertSql1 = `INSERT INTO ${account} (created,path,type,account) VALUES ('${timestamp}','${rootPath.replace(/\\/g, '/') + defaultDir}',0,'${account}');`
                                    await queryDatabase(newInsertSql)
                                }
                            })
                        })
                    }
                })
                let token = generateToken(result[0].account) //生成token
                res.send({ msg: '注册成功,云空间已创建！', code: 200 ,token})
            } else {
                res.send({ msg: '注册失败，请稍后重试！', code: 204 })
            }
        } else {
            res.send({ msg: '邮箱验证码错误！', code: 204 })
        }
    }

})
router.get('/code', async (req, res) => {
    try {
        let email = req.query.email;//前台传过来的邮箱
        let code = createSixNum();//生成的随机六位数
        let date = new Date().toLocaleString();//获取当前时间
        let sql = `select account from usersinfo where email = '${email}' `
        let result = await queryDatabase(sql)
        if (result.length > 0 && result[0].account) {
            res.send({ msg: "该邮箱账号已被注册！", code: 205 })
        } else {
            res.send({ msg: "验证码已发送", code: 200 });
            let mail = {
                from: '<867618132@qq.com>',// 发件人
                subject: '菩提网盘验证码',//邮箱主题
                to: email,//前台传过来的邮箱  收件人
                text: `您的验证码是：${code}，一小时内有效。注：非本人操作无需理会该邮件！发送时间：${date}`    // 邮件内容
            };
            let querySql = `select code from usersinfo where email = '${email}' LIMIT 1 `
            let countRes = await queryDatabase(querySql)
            let sendRes = await nodeMail(mail);//发送邮件
            if (sendRes.response) {
                if (!countRes.length > 0) {
                    let insertSql = `INSERT INTO usersinfo (email,code) VALUES ('${email}','${code}');`
                    await queryDatabase(insertSql)
                } else {
                    let updateSql = `UPDATE  usersinfo SET  code='${code}'  where email ='${email}';`
                    await queryDatabase(updateSql)
                }
            } else {
                res.send({ msg: "验证码发送失败", code: 204 });
            }
        }
    } catch (error) {
        res.send({ msg: error, code: 204 })
    }
})

module.exports = router